package com.alipay.rebate.shop.service.customer.impl;

import com.alipay.rebate.shop.core.AbstractService;
import com.alipay.rebate.shop.dao.mapper.BrowseProductMapper;
import com.alipay.rebate.shop.model.BrowseProduct;
import com.alipay.rebate.shop.service.customer.CustomerBrowseProductService;
import com.github.pagehelper.PageInfo;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class CustomerBrowseProductServiceImpl extends AbstractService<BrowseProduct> implements
    CustomerBrowseProductService {

  @Resource
  private BrowseProductMapper browseProductMapper;

  private Logger logger = LoggerFactory.getLogger(CustomerBrowseProductServiceImpl.class);

  @Override
  public PageInfo<BrowseProduct> selectUserBrowseProduct(
      Long userId,
      Integer pageNo,
      Integer pageSize) {
    logger.debug("userId , pageNo, pageSize is : {},{},{}",
        userId,pageNo,pageSize);
    List<BrowseProduct> browseProducts =
        browseProductMapper.selectBrowseProductByUserId(userId);
    PageInfo<BrowseProduct> pageInfo = new PageInfo<>(browseProducts);
    return pageInfo;
  }

  @Override
  public int insertWhenNotExists(BrowseProduct browseProduct) {
    logger.debug("BrowseProduct to insert is : {}",browseProduct);
    BrowseProduct oldRecord = browseProductMapper.selectBrowseProductByUserIdAndDate(
        browseProduct.getUserId(),
        browseProduct.getGoodsId()
    );
    logger.debug("oldRecord in database is : {}",oldRecord);
    if(oldRecord == null){
      logger.debug("not exists");
      browseProduct.setBrowseDate(new Date());
      browseProduct.setLastBrowseTime(new Date());
      browseProduct.setBrowseTimes(1);
      return browseProductMapper.insertSelective(browseProduct);
    }else{
      logger.debug("exists");
      BrowseProduct updateProduct = new BrowseProduct();
      updateProduct.setId(oldRecord.getId());
      updateProduct.setUserId(browseProduct.getUserId());
      updateProduct.setBrowseTimes(oldRecord.getBrowseTimes() + 1);
      updateProduct.setLastBrowseTime(new Date());
      logger.debug("update BrowseProduct is: {}",updateProduct);
      return browseProductMapper.updateByPrimaryKeySelective(updateProduct);
    }
  }
}
